package com.projectbox.web;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.projectbox.model.Project;
import com.projectbox.model.Resource;
import com.projectbox.model.Rule;
import com.projectbox.service.ProjectService;
import com.projectbox.service.ResourceService;
import com.projectbox.service.UserService;
import com.projectbox.utility.RuleUtility;

@Controller
@RequestMapping("/api/resource")
public class ResourceAPIController {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	private ResourceService resourceService;
	private ProjectService projectService;
	private RuleUtility ruleUtility;
	
	public void setResourceService(ResourceService resourceService) {
		this.resourceService = resourceService;
	}

	public void setProjectService(ProjectService projectService) {
		this.projectService = projectService;
	}
	
	public void setRuleUtility(RuleUtility ruleUtility) {
		this.ruleUtility = ruleUtility;
	}
	
	@RequestMapping(value = "/{pid}", method = RequestMethod.GET)
	@ResponseBody
	public List<Resource> getProjectResources(@PathVariable Long pid) {

		logger.debug("getProjectResources gets call");

		// TODO: Check access before view
		Project project = projectService.findProject(pid);
		List<Resource> resourceList = resourceService.findProjectResources(pid);
		
		logger.debug("" + project);
		logger.debug("" + resourceList);

		return resourceList;
	}
	
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	@ResponseBody
	public void processUploadProjectResources(@RequestParam(value = "pid", required = true) Long pid,
			@RequestParam(value = "uid", required = true) Long uid,
			HttpServletRequest request) throws IOException {
		
		logger.debug("upload resource");
		logger.debug("the pid " + pid);

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile multipartFile = multipartRequest.getFile("file");
		
		String name = multipartFile.getOriginalFilename();
		String description = "";
		byte[] content = multipartFile.getBytes(); // byte[]
		
		this.resourceService.addResource(content, name, description, uid, pid, (long)0);
	}
	
	
	@RequestMapping(value = "/download", method = RequestMethod.GET)
	@ResponseBody
	public void processDownloadProjectResources(@RequestParam(value = "rid", required = true) Long rid,
			HttpServletResponse response) throws IOException {
		
		logger.debug("download resource");
		logger.debug("the rid " + rid);

		Resource resource = this.resourceService.findResource(rid);
		response.setContentType(resource.getType());
		response.setContentLength(resource.getFile().length);
		response.setHeader("Content-Disposition","attachment; filename=\""
        						+ resource.getName() +"\"");
		FileCopyUtils.copy(resource.getFile(), response.getOutputStream());
	}
	
	@RequestMapping(value = "/delete", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> processDeleteProjectResources(@RequestParam(value = "rid", required = true) Long rid,
			HttpServletResponse response) throws IOException {
		
		logger.debug("processDeleteProjectResources gets call");
		
		Resource resource = this.resourceService.findResource(rid);
		boolean result = true;
		try {
			this.resourceService.removeResource(resource);
		} catch (Exception e) {
			result = false;
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", result);
	
		return map;
	}

	@RequestMapping(value = "/rule", method = RequestMethod.GET)
    public String displayRules(Model model) {
		String content = "";
		try {
			content= ruleUtility.getRule();
		} catch (IOException e) {
		}
		
		Rule rule = new Rule();
		rule.setContent(content);
		
		model.addAttribute("rule", rule);
		
		return "iRule";
	}

}
